package org.myhomework.servelet;

import org.myhomework.constant.Constants;
import org.myhomework.dao.UserDao;
import org.myhomework.entity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class ResetPasswordServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String back = req.getParameter("back");
        if (null == id) {
            id = String.valueOf(req.getSession().getAttribute(Constants.USER_ID_ATTRIBUTE));
        }
        req.setAttribute("id", id);
        req.setAttribute("back", back);
        req.getRequestDispatcher("reset-pwd.jsp").forward(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String old = req.getParameter("old");
        String _new = req.getParameter("new");
        User user = UserDao.getById(Integer.valueOf(id));
        String msg = "";
        if (Objects.equals(user.getPassword(), old)) {
            msg = "修改成功， 即将返回登录";
            UserDao.changePwd(Integer.valueOf(id), _new);
        } else {
            msg = "原密码不匹配，无法修改";
        }
        req.setAttribute("msg", msg);
        req.setAttribute("back", "/");
        // 移除session
        req.getSession().invalidate();
        req.getRequestDispatcher("ok.jsp").forward(req, resp);
    }
}
